package com.zs.batch;

import com.alibaba.fastjson.JSONObject;
import com.zs.batch.job.DataJob;
import com.zs.batch.job.HelloWordJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.*;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author lanyuping
 * @date 2022/10/27 20:56
 */
@Slf4j
@RestController
public class TestApi {

    @Autowired
    HelloWordJob helloWordJob;
    @Autowired
    DataJob dataJob;

    @Autowired
    private JobLauncher jobLauncher;

    @RequestMapping("/hello-world")
    public String helloWorld() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        // 根据时间配置每个job完成的使用参数，因为时间不一样所以参数不一样，所以任务可以重复执行
        JobParameters jobParameters = new JobParametersBuilder()
                .addDate("date", new Date())
                .addString("hello", "world")
                .toJobParameters();
        JobExecution run = jobLauncher.run(helloWordJob.helloWorldJob(), jobParameters);
        log.info("job执行结果：{}", JSONObject.toJSONString(run));
        BatchStatus status = run.getStatus();
        return JSONObject.toJSONString(status);
    }

    @RequestMapping("/data")
    public String data() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        // 根据时间配置每个job完成的使用参数，因为时间不一样所以参数不一样，所以任务可以重复执行
        JobParameters jobParameters = new JobParametersBuilder()
                .addDate("date", new Date())
                .addString("data", "data") // 传入参数 可以带入到job中
                .toJobParameters();
        JobExecution run = jobLauncher.run(dataJob.DataJob(), jobParameters);
        log.info("job执行结果：{}", JSONObject.toJSONString(run));
        BatchStatus status = run.getStatus();
        return JSONObject.toJSONString(status);
    }

}
